<!--
Date: 2025-08-13
Copyright (c) 2025 Industrial Software Feature Database
-->
<template>
  <div class="public_main">
    <div class="query">
      <el-form inline ref="queryFormRef" :model="queryParams" label-width="120px" size="small">
        <el-form-item label="对比方式:">
          <el-select v-model="queryParams.type" placeholder="请选择" @change="typeChange">
            <el-option label="全机对比" value="model"></el-option>
            <el-option label="部段对比" value="section"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="机型:">
          <el-select v-model="queryParams.modelNumber" placeholder="请选择" @change="getSectionListByModelNumber">
            <el-option v-for="item in modelNumberList" :label="item.name" :value="item.mark" :key="item.mark"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="queryParams.type == 'section'" label="部段名称:">
          <el-select v-model="queryParams.sectionNumber" placeholder="请选择" filterable>
            <el-option v-for="item in sectionNumberList" :label="item.name" :value="item.mark" :key="item.mark"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="query_btns">
          <el-button size="small" type="primary" icon="search" @click="doQuery">查询</el-button>
          <el-button size="small" type="default" icon="refresh" @click="doReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="table_div">
      <el-button size="small" type="primary" class="upload_btn" plain icon="Plus" @click="handleCompare">模型对比</el-button>
      <el-table :data="tableData" v-loading="loading">
        <!-- <el-table-column type="selection" width="55" align="left" /> -->
        <el-table-column label="模型对比创建日期" align="left" prop="createTime" fixed="left"> </el-table-column>
        <!-- <el-table-column label="所属机型" align="left" prop="fileName"> </el-table-column> -->
        <el-table-column label="对比方式" align="left" prop="type">
          <template #default="scope">
            <span>{{ scope.row.type === 'model' ? '全机对比' : '部段对比' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="待对比的BDF文件" align="left">
          <template #default="scope">
            <span>{{ scope.row.referencedObject.fileName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="对比对象（参照物）" align="left" prop="batchNumber">
          <template #default="scope">
            <span>{{ scope.row.comparedObject.fileName }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column label="上传人" align="left" prop="remarks"> </el-table-column> -->
        <el-table-column label="对比状态" align="left" prop="status">
          <template #default="scope">
            <!-- <span v-if="scope.row.status">{{ StatusMap[scope.row.status] }}</span> -->
            <el-popover
              v-if="scope.row.status == 'failed' && scope.row.message"
              placement="top-start"
              title=""
              :width="200"
              trigger="click"
             content="对比失败，请联系管理人员"
            >
              <template #reference>
                <el-text class="mx-1" :type="typeMap[scope.row.status]">{{ StatusMap[scope.row.status] }}</el-text>
              </template>
            </el-popover>
            <el-text v-else class="mx-1" :type="typeMap[scope.row.status]">{{ StatusMap[scope.row.status] }}</el-text>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="left" width="250">
          <template #default="scope">
            <el-button v-if="scope.row.status == 'completed'" size="small" link type="primary" icon="View" @click="view(scope.row)">查看对比结果</el-button>
            <el-button v-if="scope.row.status == 'failed'" size="small" link type="danger" icon="Warning" @click="logError(scope.row)">查看失败原因</el-button>
            <el-button size="small" link type="primary" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagenation">
        <pagination
          v-show="total > 0"
          style="margin-top: 0;"
          v-model:page="queryParams.pageQuery.pageNum"
          v-model:limit="queryParams.pageQuery.pageSize"
          :total="total"
          :background="false"
          layout="total, sizes, prev, pager, next, jumper"
          @pagination="handleCurrentChange"
        />
      </div>
    </div>
    <Contrast
      v-if="addVisible"
      :addVisible="addVisible"
      :operateType="operateType"
      :compareRecordId="compareRecordId"
      :compareStatus="compareStatus"
      @handleEvent="handleEvent"
    />
    <el-dialog
      v-model="logVisible"
      title="失败原因"
      width="30%"
      :before-close="handleClose"
    >
      <el-text style="text-align: center;" class="mx-2" type="danger">对比失败，请联系管理人员</el-text>
      <!-- <template #footer>
        <span class="dialog-footer">
          <el-button @click="logVisible = false">返回</el-button>
        </span>
      </template> -->
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, onMounted } from 'vue';
import { getCompareList, getCompareDetail, addCompareTask, getMeshModelStructureList, deleteCompare } from '@/api/dataAcquisition';
import Contrast from './Contrast.vue';
const emits = defineEmits(['handleEvent']);
const { proxy } = getCurrentInstance();
const tableData = ref([]);
const addVisible = ref(false);
const modelNumberList = ref([]);
const sectionNumberList = ref([]);
const compareRecordId = ref(null);
const operateType = ref('');
const compareStatus = ref('');
const queryParams = ref({
  type: '',
  modelNumber: '',
  sectionNumber: '',
  pageQuery: {
    pageNum: 1,
    pageSize: 10,
    orderByColumn: 'createTime',
    isAsc: 'descending'
  }
});
const total = ref(0);
const loading = ref(false);
const StatusMap = {
  'in_progress': '对比中……',
  'completed': '对比完成',
  'failed': '对比失败',
}
const typeMap = {
  'in_progress': 'warning',
  'completed': 'success',
  'failed': 'danger',
}
const logVisible = ref(false);
const errorMessage = ref('');
const logError = (row) => {
    // errorMessage.value = row.message;
    // logVisible.value = true;
  compareRecordId.value = row._id;
  operateType.value = 'View';
  compareStatus.value = row.status;
  addVisible.value = true;
}
const handleView = () => {
  preViewVisible.value = false;
};
const typeChange = (val) => {
  if (val == 'model') {
    queryParams.value.sectionNumber = '';
  }
}
// 新增对比任务
const handleCompare = () => {
  operateType.value = 'Add';
  compareRecordId.value = null;
  addVisible.value = true;
  // emits('handleEvent', { component: 'List', type: 'add' });
}
// 预览
const view = (row) => {
  compareRecordId.value = row._id;
  operateType.value = 'View';
  compareStatus.value = row.status;
  addVisible.value = true;
};
const handleCurrentChange = () => {
  doQuery();
};
//查询数据列表
const doQuery = () => {
  loading.value = true;
  tableData.value = [];
  getCompareList(queryParams.value)
    .then((res) => {
      // 处理数据
      loading.value = false;
      total.value = res?.total;
      tableData.value = res.rows;
    })
    .catch(() => {
      loading.value = false;
    }).finally(() => {
      loading.value = false;
    });
};
// 回调函数
const handleEvent = (data) => {
  addVisible.value = false;
  if (data?.type === 'refresh') {
    doQuery();
  } else if (data?.type === 'cancel') {

  };
};
const doReset = () => {
  queryParams.value = {
    type: '',
    modelNumber: '',
    sectionNumber: '',
    pageQuery: {
      pageNum: 1,
      pageSize: 10,
      orderByColumn: 'createTime',
      isAsc: 'descending'
    }
  };
  sectionNumberList.value = [];
  doQuery();
};
// 打开弹窗方法
const handleVisible = (param, data) => {
  if (param == 'import') {
    emits('handleEvent', { component: 'List', type: 'add' });
  }
};
//删除
const handleDelete = (row) => {
  ElMessageBox.confirm('是否确认删除当前数据项？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteCompare(row._id)
    .then((res) => {
      if (res) {
        ElMessage({ showClose: true, message: '删除成功。', type: 'success' });
        doQuery();
      }
    })
    .catch(() => {
      ElMessage({ showClose: true, message: '删除失败。', type: 'error' });
    });
  });
};
const getModelList = () => {
  getMeshModelStructureList({parentId: 0, pageSize: 999}).then(res => {
    if (res) {
      modelNumberList.value = res.rows;
    }
  })
}
// 查询机型下的部段信息
const getSectionListByModelNumber = (modelNumber) => {
  if (!modelNumber) {
    return;
  }
  queryParams.value.sectionNumber = '';
  let modelId = modelNumberList.value.find(item => item.mark == modelNumber)?.id;
  getMeshModelStructureList({parentId: modelId, pageSize: 999}).then(res => {
    if (res) {
      sectionNumberList.value = res.rows;
    }
  })
}
onMounted(() => {
  doQuery();
  getModelList();
});
</script>
<style lang="scss" scoped>
.public_main {
  padding: 20px 5px 20px 20px;
  .query {
    border: 1px solid #dddddd7a;
    padding: 20px 10px 0 10px;
    .query_btns {
      padding-left: 100px;
    }
  }
  .table_div {
    margin-top: 10px;
    border: 1px solid #dddddd7a;
    padding-bottom: 10px;
    .upload_btn {
      margin: 10px 10px;
    }
    .pagenation {
      display: flex;
      justify-content: end;
      margin-top: 10px;
    }
  }
  :deep(.el-form-item__content) {
    width: 220px;
  }
  :deep(.el-tree-node__label) {
    font-size: 12px;
    color: #606266;
  }
}
</style>
      